#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>
#include <QDebug>
#include <QList>
#include <QMessageBox>
#include <QShortcut>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setLayout(ui->verticalLayout);
    ui->widget_bottom->setLayout(ui->horizontalLayout_2);

    // 编码选择框
    connect(ui->codeSel,SIGNAL(currentIndexChanged(int)),this,SLOT(on_codeChange()));
    // 行列定位
    connect(ui->textEdit,SIGNAL(cursorPositionChanged()),this,SLOT(on_CursorChange()));

    // 快捷键的设置
    QShortcut *open_shortcut = new QShortcut(QKeySequence("ctrl+o"),this);
    QShortcut *save_shortcut = new QShortcut(QKeySequence("ctrl+s"),this);
    connect(open_shortcut,&QShortcut::activated,[&](){
        Widget::on_btnOpen_clicked();
    });
    connect(save_shortcut,&QShortcut::activated,[&](){
         f.resize(0);
        Widget::on_btnSave_clicked();
    });
    // 字体的放大与缩小 =>使用快捷键的方式
    QShortcut *fontadd_shortcut = new QShortcut(QKeySequence("alt+="),this);
    connect(fontadd_shortcut,&QShortcut::activated,[&](){

        QFont font = ui->textEdit->font();
        int size = font.pointSize();
        if(size == 50) return;
        font.setPointSize(++size);
        ui->textEdit->setFont(font);
        qDebug()<< size ;
    });
    QShortcut *fontsub_shortcut = new QShortcut(QKeySequence("alt+-"),this);
    connect(fontsub_shortcut,&QShortcut::activated,[&](){

        QFont font = ui->textEdit->font();
        int size = font.pointSize();
        if(size == 10) return;
        font.setPointSize(--size);
        ui->textEdit->setFont(font);
        qDebug()<< size ;
    });

}

Widget::~Widget()
{
    delete ui;
}

// 事件过滤器
bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::Wheel){
        if(QGuiApplication::keyboardModifiers() == Qt::ControlModifier){
            qDebug() << "ctrl + wheel";
        }
    }
}


void Widget::on_btnOpen_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
         tr("选择一个文本文件打开"), "F:/", tr("文本文件 (*.txt)"));
    ui->textEdit->clear();// 清空之前存在的内容
    qDebug() << fileName;
    f.setFileName(fileName);
    this->setWindowTitle(fileName + "--坤坤记事本");
    if (!f.open(QIODevice::ReadWrite | QIODevice::Text)) {
        qDebug() << "打开失败=>" << f.errorString();
        return;
    }

    QTextStream fs(&f);
    fs.setCodec(ui->codeSel->currentText().toStdString().c_str());
    QString content = fs.readAll();


    if (content.isEmpty()) {
        qDebug() << "文件为空";
        return;
    }

    ui->textEdit->append(content);//以追加形式显示到控件 使用setText如果是长文本就会覆盖前面的
}

void Widget::on_btnSave_clicked()
{
    if(!f.isOpen()){
        QString fileName = QFileDialog::getSaveFileName(this, tr("保存文件至"),
                                   "F:/untitled.txt",
                                   tr("文本文件 (*.txt)"));

        f.setFileName(fileName);
        if (!f.open(QIODevice::ReadWrite | QIODevice::Text)) {
            qDebug() << "打开失败" << f.errorString();
            return;
        }
        this->setWindowTitle(fileName + "--坤坤记事本");
    }

        QTextStream fs(&f);
        fs.setCodec(ui->codeSel->currentText().toStdString().c_str());
        QString content = ui->textEdit->toPlainText();
        fs << content;
        f.close();
}

void Widget::on_btnClose_clicked()
{
    // 文本框有内容才提示保存,没有就直接退出程序
    if(ui->textEdit->toPlainText().length() > 0){
    int ret = QMessageBox::warning(this, tr("警告"),
                                   tr("文件已修改.\n"
                                      "是否要保存为新文件?"),
                                   QMessageBox::Save | QMessageBox::Discard
                                   | QMessageBox::Cancel,
                                   QMessageBox::Save);
    switch (ret) {
        case QMessageBox::Save:
            // Save was clicked
        f.resize(0);
        on_btnSave_clicked();
            break;
        case QMessageBox::Discard:
            // Don't Save was clicked
            ui->textEdit->clear();
            if(f.isOpen()){
                f.close();
                qDebug() << "已关闭";
                this->setWindowTitle("坤坤记事本");
            }
            this->close();
            break;
        case QMessageBox::Cancel:
            // Cancel was clicked
            break;
        default:
            // should never be reached
            break;
      }
    }
    else{
        this->close();
    }

}

void Widget::on_codeChange()
{
    ui->textEdit->clear();
    if(f.isOpen()){
        f.seek(0);
        QTextStream fs(&f);
        fs.setCodec(ui->codeSel->currentText().toStdString().c_str());
        QString content = fs.readAll();
        ui->textEdit->append(content);
    }
}

void Widget::on_CursorChange()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    //qDebug() << cursor.blockNumber() + 1 << "," << cursor.columnNumber() + 1;
    QString bnum = QString::number(cursor.blockNumber() + 1);
    QString cnum = QString::number(cursor.columnNumber() + 1);
    QString s = "行: " + bnum + " 列: " + cnum ;
    ui->labelPosition->setText(s);
    // 设置当前行高亮
    QList<QTextEdit::ExtraSelection> extraselection;
    QTextEdit::ExtraSelection ext;
    ext.cursor = ui->textEdit->textCursor();
    QBrush brush(Qt::yellow);
    ext.format.setBackground(brush);
    ext.format.setProperty(QTextFormat::FullWidthSelection,true);
    extraselection.append(ext);
    ui->textEdit->setExtraSelections(extraselection);
}
